package edu.hda.pt.client.connections.mina;

import org.apache.mina.core.session.IoSession;

import edu.hda.pt.client.connections.PTClientMINA;
import edu.hda.pt.utils.Stream.StreamState;

/**
 * Event handler for receiving asynchronous messages
 * 
 * @author Marc Hammerton
 * 
 */
public class AsyncClientProtocolHandler extends ClientProtocolHandler {

	private PTClientMINA client;

	/**
	 * Constructor setting the client object
	 * 
	 * @param client
	 *            - client object
	 */
	public AsyncClientProtocolHandler(PTClientMINA client) {
		this.client = client;
	}

	/**
	 * This method is called whenever an exception is caught. It closes the
	 * session and prints the exception.
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(IoSession,
	 *      Throwable)
	 */
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) {
		session.close(true);
		System.out.println(client.clientID + " Exception:");
		System.out.println(cause);
	}

	/**
	 * This method is called when a message from the server is received. It
	 * notifies the client that a message is received.
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(IoSession,
	 *      Object)
	 */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if (client.stream.getState() != StreamState.RUNNING) {
			client.stream.setState(StreamState.RUNNING);
		}
		synchronized (client) {
			client.notify();
		}
	}

	/**
	 * @see edu.hda.pt.client.connections.mina.ClientProtocolHandler#responseReceived()
	 */
	@Override
	public String responseReceived() {
		return null;
	}
}
